package com.wannengbang.storemobile.homepage;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.wannengbang.storemobile.R;
import com.wannengbang.storemobile.base.BaseActivity;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.bean.CreateOrderBean;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.homepage.model.IHomePageModel;
import com.wannengbang.storemobile.utils.CashierInputFilter;
import com.wannengbang.storemobile.utils.FastClickUtils;
import com.wannengbang.storemobile.utils.NumberFormatUtils;
import com.wannengbang.storemobile.utils.ToastUtil;
import com.wannengbang.storemobile.widget.AppTitleBar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ScanCodeActivity extends BaseActivity {

    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    private IHomePageModel homePageModel;
    private String order_no;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private int count;
    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {
            count++;
            if (count >= 30) {
                ToastUtil.showShort("收款失败");
                dismissProgress();
                mHandler.removeCallbacks(mTimeCounterRunnable);
            } else {
                requestStoreOrderShow();
            }
        }
    };
    private String moneyUnit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_code);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        InputFilter[] filters = {new CashierInputFilter()};
        editMoney.setFilters(filters);
    }

    @OnClick({R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                String money = editMoney.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    ToastUtil.showShort("请输入金额");
                    return;
                }
                if (Double.parseDouble(money) <= 0) {
                    ToastUtil.showShort("金额必须大于0元");
                    return;
                }
                IntentIntegrator integrator = new IntentIntegrator(mActivity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(false);
                integrator.setCaptureActivity(QRActivity.class);
                integrator.initiateScan();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫描取消", Toast.LENGTH_LONG).show();
            } else {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                String code = scanResult.getContents();
                requestStoreOrderAdd(code);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    private void requestStoreOrderAdd(String auth_code) {
        if (!NumberFormatUtils.isNumeric(auth_code)) {
            ToastUtil.showShort("请扫描付款码");
            return;
        }
        String money = editMoney.getText().toString();
        //钱数 单位分
        moneyUnit = String.valueOf(Double.parseDouble(money) * 100);
        moneyUnit = moneyUnit.substring(0, moneyUnit.indexOf("."));
        showProgress("收款中.....");
        homePageModel.requestStoreOrderAdd("1", moneyUnit, auth_code, "", new DataCallBack<CreateOrderBean>() {
            @Override
            public void onSuccessful(CreateOrderBean bean) {
                order_no = bean.getData().getOrder_no();
                requestStoreOrderScanCode(moneyUnit, auth_code);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    /**
     * 支付订单
     */
    private void requestStoreOrderScanCode(String moneyUnit, String auth_code) {
        homePageModel.requestStoreOrderScanCode("1", moneyUnit, auth_code, "", order_no, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                requestStoreOrderShow();
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    /**
     * 轮询订单
     */
    private void requestStoreOrderShow() {
        homePageModel.requestStoreOrderShow(order_no, new DataCallBack<CreateOrderBean>() {
            @Override
            public void onSuccessful(CreateOrderBean bean) {
                if (bean.getData().getPay_status() == 1) {
                    String money = editMoney.getText().toString();
                    Intent intent = new Intent(mActivity, CashierSuccessActivity.class);
                    intent.putExtra("money", money);
                    startActivity(intent);
                    ToastUtil.showShort("收款成功");
                    dismissProgress();
                    editMoney.setText("");
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else if (bean.getData().getPay_status() == 2) {
                    ToastUtil.showShort(bean.getData().getOrder_remark());
                    dismissProgress();
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else {
                    mHandler.postDelayed(mTimeCounterRunnable, 1 * 1000);
                }
                Log.d("--------", "" + order_no);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时任务
        mHandler.removeCallbacks(mTimeCounterRunnable);
    }

    private Dialog progress;

    public void showProgress(String message) {
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);
        try {
            progress.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgress() {
        if (progress == null) {
            return;
        }
        try {
            progress.dismiss();
            progress = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
